import 'package:flutter/material.dart';
import '../models/anniversary.dart';
import '../services/storage_service.dart';

class AnniversaryReminderWidget extends StatefulWidget {
  const AnniversaryReminderWidget({Key? key}) : super(key: key);

  @override
  _AnniversaryReminderWidgetState createState() => _AnniversaryReminderWidgetState();
}

class _AnniversaryReminderWidgetState extends State<AnniversaryReminderWidget> {
  final StorageService _storageService = StorageService();
  List<Anniversary> _anniversaries = [];

  @override
  void initState() {
    super.initState();
    _loadAnniversaries();
  }

  Future<void> _loadAnniversaries() async {
    final anniversaries = await _storageService.getAnniversaries();
    setState(() {
      _anniversaries = anniversaries;
    });
  }

  Future<void> _addAnniversary() async {
    final TextEditingController titleController = TextEditingController();
    DateTime selectedDate = DateTime.now();
    bool isYearly = true;
    Color selectedColor = Colors.pink;

    return showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('添加纪念日'),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TextField(
                      controller: titleController,
                      decoration: const InputDecoration(
                        labelText: '标题',
                        hintText: '例如：结婚纪念日',
                      ),
                    ),
                    const SizedBox(height: 16),
                    ListTile(
                      title: const Text('日期'),
                      subtitle: Text(
                        '${selectedDate.year}年${selectedDate.month}月${selectedDate.day}日',
                      ),
                      onTap: () async {
                        final DateTime? picked = await showDatePicker(
                          context: context,
                          initialDate: selectedDate,
                          firstDate: DateTime(1900),
                          lastDate: DateTime(2100),
                        );

                        if (picked != null && picked != selectedDate) {
                          setState(() {
                            selectedDate = picked;
                          });
                        }
                      },
                    ),
                    SwitchListTile(
                      title: const Text('每年重复'),
                      value: isYearly,
                      onChanged: (value) {
                        setState(() {
                          isYearly = value;
                        });
                      },
                    ),
                    const SizedBox(height: 16),
                    const Text('选择颜色'),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        _buildColorOption(Colors.pink, selectedColor, (color) {
                          setState(() {
                            selectedColor = color;
                          });
                        }),
                        _buildColorOption(Colors.red, selectedColor, (color) {
                          setState(() {
                            selectedColor = color;
                          });
                        }),
                        _buildColorOption(Colors.orange, selectedColor, (color) {
                          setState(() {
                            selectedColor = color;
                          });
                        }),
                        _buildColorOption(Colors.green, selectedColor, (color) {
                          setState(() {
                            selectedColor = color;
                          });
                        }),
                        _buildColorOption(Colors.blue, selectedColor, (color) {
                          setState(() {
                            selectedColor = color;
                          });
                        }),
                      ],
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () async {
                    if (titleController.text.isNotEmpty) {
                      final anniversary = Anniversary(
                        id: DateTime.now().millisecondsSinceEpoch.toString(),
                        title: titleController.text,
                        date: selectedDate,
                        isYearly: isYearly,
                        color: selectedColor,
                      );

                      await _storageService.addAnniversary(anniversary);
                      _loadAnniversaries();
                      Navigator.pop(context);
                    }
                  },
                  child: const Text('添加'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildColorOption(Color color, Color selectedColor, Function(Color) onSelect) {
    final bool isSelected = color.value == selectedColor.value;

    return GestureDetector(
      onTap: () => onSelect(color),
      child: Container(
        width: 30,
        height: 30,
        decoration: BoxDecoration(
          color: color,
          shape: BoxShape.circle,
          border: Border.all(
            color: isSelected ? Colors.white : Colors.transparent,
            width: 2,
          ),
          boxShadow: isSelected
              ? [
            BoxShadow(
              color: Colors.black.withOpacity(0.3),
              blurRadius: 4,
              spreadRadius: 2,
            ),
          ]
              : null,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '纪念日提醒',
                  style: Theme.of(context).textTheme.headline6,
                ),
                IconButton(
                  icon: const Icon(Icons.add),
                  onPressed: _addAnniversary,
                ),
              ],
            ),
            const SizedBox(height: 8),
            _anniversaries.isEmpty
                ? const Center(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Text('还没有纪念日，点击右上角添加'),
              ),
            )
                : ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: _anniversaries.length,
              itemBuilder: (context, index) {
                final anniversary = _anniversaries[index];
                return ListTile(
                  leading: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: anniversary.color.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Text(
                        anniversary.daysRemaining.toString(),
                        style: TextStyle(
                          color: anniversary.color,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                  title: Text(anniversary.title),
                  subtitle: Text(
                    '${anniversary.date.year}年${anniversary.date.month}月${anniversary.date.day}日',
                  ),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () async {
                      await _storageService.deleteAnniversary(anniversary.id);
                      _loadAnniversaries();
                    },
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

